package com.demo.chapter10optional;

import java.util.Optional;
import java.util.Properties;

//重构现有代码
public class Reconstruction {

	//重构Integer.parseInt(s)
	public static Optional<Integer> stringToInt(String s){
		try{
			return Optional.of(Integer.parseInt(s));
		}catch(NumberFormatException e){
			return Optional.empty();
		}
	}
	
	//传统的方式
	public static int readDurationImperative(Properties props, String name) {
        String value = props.getProperty(name);
        if (value != null) {
            try {
                int i = Integer.parseInt(value);
                if (i > 0) {
                    return i;
                }
            } catch (NumberFormatException nfe) { }
        }
        return 0;
    }
	
	//使用Optional改造后
	public static int readDurationWithOptional(Properties props, String name) {
        return Optional.ofNullable(props.getProperty(name))
                .flatMap(Reconstruction::stringToInt)
                .filter(i -> i > 0).orElse(0);
    }
	
	public static void main(String[] args) {
		Properties props = new Properties();
        props.setProperty("a", "5");
        props.setProperty("b", "true");
        props.setProperty("c", "-3");

        //只有当输入的值是大于0的自然数时，返回数字本身，除此以外都返回0
        System.out.println(readDurationImperative(props, "a"));
        System.out.println(readDurationImperative(props, "b"));
        System.out.println(readDurationImperative(props, "c"));
        System.out.println(readDurationImperative(props, "d"));

        System.out.println(readDurationWithOptional(props, "a"));
        System.out.println(readDurationWithOptional(props, "b"));
        System.out.println(readDurationWithOptional(props, "c"));
        System.out.println(readDurationWithOptional(props, "d"));
	}
	
}
